<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }

        h3 {
            padding-right: 20px;
        }
    </style>
</head>

<body>
    <div class="box">
        <h3>距离端午节还剩：</h3>
        <p class="time"></p>
    </div>

    <script>
        // 准备两个时间节点
        var time1 = new Date('2020-6-25 00:00:00')
        // var time2 = new Date()

        // 获取页面中现在存在的p标签
        var p = document.querySelector('div p')

        // 计算两个时间节点之间的时间差
        function timeDiff(time1, time2) {
            var diff = Math.floor(Math.abs(time1.getTime() - time2.getTime()) / 1000)
            var day = Math.floor(diff / (60 * 60 * 24))
            var hours = Math.floor(diff % (60 * 60 * 24) / (60 * 60))
            var minutes = Math.floor(diff % (60 * 60) / 60)
            var seconds = diff % 60
            var obj = {}
            obj.day = day
            obj.hours = hours
            obj.minutes = minutes
            obj.seconds = seconds
            return obj
        }

        // 书写一个定时器
        setInterval(function () {
            // 这里的代码才会每间隔一秒执行一次
            // 获取时间差
            var time2 = new Date()
            var res = timeDiff(time1, time2)

            // 写入页面里面
            // 每间隔一秒都要组装一次最新的字符串
            var str = '<span>' + res.day + '天</span><span>' + res.hours + '小时</span><span>' + res.minutes +
                '分钟</span><span>' + res.seconds + '秒钟</span>'
            // 获取p元素，因为不需要每间隔一秒都获取一次
            // 所以这段代码写在定时器外面
            // 因为每间隔一秒都要覆盖式的写入一次
            p.innerHTML = str
        }, 1000)
    </script>
</body>

</html>